
package webshop.web;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.transaction.UserTransaction;
import javax.persistence.*;

import webshop.data.Product;
import webshop.data.ShoppingBasket;
import webshop.data.Person;

/**
 * Adds a product to the users shoppingbasket.
 * @author Ohm & simon.
 */
public class ShoppingBasketAddProductServlet extends AbstractSuperServlet {

    @Resource
    UserTransaction tx;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        EntityManager em = emf.createEntityManager();

        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        try {
            tx.begin();
            // Initialise variables.
            Person person = null;
            int quantity = 0;
            String productName = null;

            try {
                //Get paramters and check them.
                quantity = Integer.parseInt(request.getParameter("quantity"));
                productName = request.getParameter("product");
            } catch (Exception e) {
                out.println("Parameter error.");
                out.println("<br/>");
                out.println("Please use a integer for quantity and alpabetic characters on product name");
            }

            //Check if person is logged in.
            PersonUtil personUtil = new PersonUtil(em, request);
            person = personUtil.isActive();

            // if person is logged on, take the product, check the stock and put
            // it in the basket.
            if (person != null) {
                try {
                    out.println("<p>You are logged in:</p>");
                    ShoppingBasket basket = personUtil.getShoppingBasket(person);

                    Product product = personUtil.findProduct(productName);
                    if(product != null){
                        //Check Stock.
                        if(product.getStock() - quantity <= 0){
                            out.println(" but not enough stock of product " + product.getName());
                        } else{
                        personUtil.addToBasket(product, basket, quantity);
                        // Reduce stock.
                        product.reduceStock(quantity);
                        out.println(" and product found and added to your basket!");
                        }
                    }else {
                        out.println("Product not found, check you spelling.");
                    }


                } catch (Exception e) {
                    out.println(" but product or basket was not found");
                }
            } else{
                out.println("<br/>");
                out.println("Please login!");
            }

            tx.commit();
        } catch (Exception e) {
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        } finally {
            // 5 sec redirect.
            out.println("<meta http-equiv=Refresh content=2;url=productPage.html> ");
            out.println("<br/>");
            out.println("Redirect in 2 sec.");
            out.close();
        }
    }
}
